package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.enums.ResultEnums;
import com.dongdongshop.pojo.TbSeller;
import com.dongdongshop.service.TbSellerService;
import com.dongdongshop.uitl.ShiroUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("TbSeller")
public class TbSellerController {

    //注入service
    @DubboReference
    private TbSellerService tbSellerService;


    //注册(添加)
    @ResponseBody
    @RequestMapping("addTbSeller")
    public Result addTbUser(TbSeller tbSeller) {
        try {
            //根据sellerId查询数据是否存在
            List<TbSeller> list = tbSellerService.showbysellerId(tbSeller.getSellerId());
            if (list.size() == 0){
                String s = ShiroUtils.generateSalt(6);
                //需要加密的密码
                String pwd = tbSeller.getPassword();
                //加密方法
                String md5 = ShiroUtils.encryptPassword("MD5", pwd, s, 3);
                tbSeller.setBrief(s);
                tbSeller.setPassword(md5);
                tbSellerService.addTbSeller(tbSeller);
                return Result.response(ResultEnums.REGISTER_SUCCESS);
            }else
            return Result.response(ResultEnums.REGISTER_ERRORNAME);
        }catch (Exception e){
            System.out.println(e);
            return Result.response(ResultEnums.REGISTER_ERROR);
        }
    }

    //登录;逻辑
    @ResponseBody
    @RequestMapping("login")
    public Result login(TbSeller tbSeller){

        //使用shiro编写认证操作
        //获取Subject对象
        Subject subject = SecurityUtils.getSubject();
        //封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(tbSeller.getSellerId(),tbSeller.getPassword());
        //执行登录方法
        Result result = null;
        try {
            //登录成功
            subject.login(token);
            result = Result.response(ResultEnums.LOGIN_SUCCESS);
        }catch (UnknownAccountException e){
            //用户名不存在
            result = Result.response(ResultEnums.LOGIN_ERRORNAME);
        }catch (IncorrectCredentialsException e){
            result = Result.response(ResultEnums.LOGIN_ERRORPASSWORD);
        }
        return result;
    }
}
